import uuid

from django.contrib.auth.hashers import make_password, check_password
from django.core.cache import cache, caches
from django.core.mail import send_mail
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.template import loader
from django.urls import reverse

from AXF.settings import MEDIA_KEY_PREFIX
from App.models import MainWheel, MainNav, MainMustBuy, MainShop, FoodType, Goods, AXFUser, Cart, Order, OrderGoods
from App.views_constant import ALL_TYPE, ORDER_TOTAL, ORDER_PRICE_UP, ORDER_PRICE_DOWN, ORDER_SALE_UP, ORDER_SALE_DOWN, \
    HTTP_USER_EXIST, HTTP_OK, ORDER_STATUS_NOT_PAY, ORDER_STATUS_NOT_RECEIVE, ORDER_STATUS_NOT_SEND
from App.views_helper import hash_str, send_email_activate, get_total_price

# 直接输入IP或者域名进行跳转
def index(request):
    return redirect(reverse('axf:home'))


def home(request):
    main_wheels = MainWheel.objects.all()
    main_navs = MainNav.objects.all()
    main_mustbuys = MainMustBuy.objects.all()
    main_shops = MainShop.objects.all()
    main_shop_1 = main_shops[0:1]
    main_shop_2 = main_shops[1:3]
    main_shop_3 = main_shops[3:7]
    main_shop_4 = main_shops[7:11]

    data = {
        "title": "首页",
        "main_wheels": main_wheels,
        "main_navs": main_navs,
        "main_mustbuys": main_mustbuys,
        "main_shop_1": main_shop_1,
        "main_shop_2": main_shop_2,
        "main_shop_3": main_shop_3,
        "main_shop_4": main_shop_4,
    }

    return render(request, 'main/home.html', context=data)


def market(request):
    return redirect(reverse('axf:market_with_params', kwargs={
        "typeid": 104749,
        "childcid": 0,
        "order_rule": 0,
    }))


def market_with_params(request, typeid, childcid, order_rule):
    foodtypes = FoodType.objects.all()
    goods_list = Goods.objects.filter(categoryid=typeid)

    # 如果默认是"全部类型，则不筛选，其他情况要筛选商品子类型"
    if childcid == ALL_TYPE:
        pass
    else:
        goods_list = goods_list.filter(childcid=childcid)

    if order_rule == ORDER_TOTAL:
        pass
    elif order_rule == ORDER_PRICE_UP:
        goods_list = goods_list.order_by("price")
    elif order_rule == ORDER_PRICE_DOWN:
        goods_list = goods_list.order_by("-price")
    elif order_rule == ORDER_SALE_UP:
        goods_list = goods_list.order_by("productnum")
    elif order_rule == ORDER_SALE_DOWN:
        goods_list = goods_list.order_by("-productnum")
    foodtype = foodtypes.get(typeid=typeid)
    """
    全部分类:0#进口水果:103534#国产水果:103533
    根据#切割：
        ['全部分类:0','进口水果:103534','国产水果:103533' ]
        再根据:切割
            [[全部分类,0],[进口水果,103534],[国产水果,103533]]
    """
    foodtypechildnames = foodtype.childtypenames
    foodtypechildname_lists = foodtypechildnames.split("#")
    foodtypechildname_list_lists = []

    for foodtypechildname_list in foodtypechildname_lists:
        foodtypechildname_list_lists.append(foodtypechildname_list.split(":"))

    order_rule_list = [
        ['综合排序', ORDER_TOTAL],
        ['价格升序', ORDER_PRICE_UP],
        ['价格降序', ORDER_PRICE_DOWN],
        ['销量升序', ORDER_SALE_UP],
        ['销量降序', ORDER_SALE_DOWN],
    ]
    data = {
        "title": "闪购",
        "foodtypes": foodtypes,
        "goods_lists": goods_list,
        "typeid": int(typeid),
        "foodtypechildname_list_lists": foodtypechildname_list_lists,
        "childcid": childcid,
        "order_rule_list": order_rule_list,
        "order_rule_now": order_rule
    }

    return render(request, 'main/market.html', context=data)


def cart(request):
    carts = Cart.objects.filter(c_user=request.user)

    is_all_select = not carts.filter(c_is_select=False).exists()

    data = {
        'title': "购物车",
        'carts': carts,
        'is_all_select': is_all_select,
        'total_price': get_total_price(),
    }

    return render(request, 'main/cart.html', context=data)


def mine(request):
    user_id = request.session.get("user_id")

    data = {
        "title": "我的",
        "is_login": False
    }

    if user_id:
        user = AXFUser.objects.get(pk=user_id)
        data['username'] = user.u_username
        data['is_login'] = True
        data['icon'] = MEDIA_KEY_PREFIX + user.u_icon.url
        data['order_not_pay'] = Order.objects.filter(o_user=user).filter(o_status=ORDER_STATUS_NOT_PAY).count()
        data['order_not_receive'] = Order.objects.filter(o_user=user).filter(
            o_status__in=[ORDER_STATUS_NOT_RECEIVE, ORDER_STATUS_NOT_SEND]).count()

    return render(request, 'main/mine.html', context=data)


def register(request):
    if request.method == "GET":
        data = {
            "title": "注册"
        }
        return render(request, 'user/register.html', context=data)

    elif request.method == "POST":
        username = request.POST.get("username")
        email = request.POST.get("email")
        password = request.POST.get("password")
        icon = request.FILES.get("icon")

        # 1.用哈希算法给密码生成摘要
        # password = hash_str(password)

        # 2.也可以用django自带的hash造密码函数，综合了时间散列，每次生成的加密数据都不一样，同时还有check_password去校验正确性
        password = make_password(password)

        user = AXFUser()
        user.u_username = username
        user.u_email = email
        user.u_password = password
        user.u_icon = icon

        user.save()
        u_token = uuid.uuid4().hex
        # 选择redis cache
        cache = caches['redis_backend']
        cache.set(u_token, user.id, timeout=60 * 60 * 24)

        send_email_activate.delay(username, email, u_token)

        return redirect(reverse("axf:login"))


def login(request):
    if request.method == "GET":
        error_message = request.session.get('error_message')

        data = {
            "title": "登录"
        }
        if error_message:
            del request.session['error_message']
            data['error_message'] = error_message

        return render(request, 'user/login.html', context=data)

    elif request.method == "POST":

        username = request.POST.get("username")
        password = request.POST.get("password")
        users = AXFUser.objects.filter(u_username=username)

        if users.exists():
            user = users.first()
            if check_password(password, user.u_password):
                if user.is_active:
                    # 通过session将用户的id存下来
                    request.session['user_id'] = user.id
                    return redirect(reverse('axf:mine'))
                else:
                    request.session['error_message'] = '用户未激活'
                    return redirect(reverse('axf:login'))
            else:
                request.session['error_message'] = '密码错误'
                return redirect(reverse('axf:login'))

        request.session['error_message'] = '用户不存在'
        return redirect(reverse('axf:login'))


# 用以ajax去异步校验用户名有效性
def checkuser(request):
    username = request.GET.get("username")

    users = AXFUser.objects.filter(u_username=username)

    data = {
        "status": HTTP_OK,
        "msg": "该用户名可用"
    }

    if users.exists():
        data['status'] = HTTP_USER_EXIST
        data['msg'] = '用户名已存在'
    else:
        pass

    return JsonResponse(data=data)


# 用以ajax去异步校验邮箱有效性
def checkmail(request):
    email = request.GET.get("email")
    mails = AXFUser.objects.filter(u_email=email)

    data = {
        "status": HTTP_OK,
        "msg": "该邮箱可用"
    }

    if mails.exists():
        data['status'] = HTTP_USER_EXIST
        data['msg'] = '邮箱已存在'
    else:
        pass

    return JsonResponse(data=data)


# 退出
def logout(request):
    request.session.flush()

    return redirect(reverse('axf:mine'))


def activate(request):
    cache = caches['redis_backend']

    u_token = request.GET.get("u_token")

    user_id = cache.get(u_token)

    data = {}

    if user_id:
        # 只能用一次
        cache.delete(u_token)

        user = AXFUser.objects.get(pk=user_id)
        # 如果当前session中的token有对应user
        if user:
            # 如果这个user没有激活，就激活
            if not user.is_active:
                user.is_active = True
                user.save()
                return redirect(reverse('axf:login'))
            else:
                data['fail_reason'] = "用户已经激活"
        else:
            data['fail_reason'] = "用户不存在"
    else:
        data['fail_reason'] = "链接失效"

    return render(request, 'user/activate_fail.html', context=data)


# 添加商品到购物车
def add_to_cart(request):
    goodsid = request.GET.get('goodsid')

    carts = Cart.objects.filter(c_user=request.user).filter(c_goods_id=goodsid)

    # 如果购物车中有商品信息，就加1
    if carts.exists():
        cart_obj = carts.first()
        cart_obj.c_goods_num = cart_obj.c_goods_num + 1
    # 没有就新增
    else:
        cart_obj = Cart()
        cart_obj.c_goods_id = goodsid
        cart_obj.c_user = request.user

    cart_obj.save()

    data = {
        'status': 200,
        'msg': "添加成功",
        'c_goods_num': cart_obj.c_goods_num,
    }
    return JsonResponse(data)


# 变更选中商品的状态
def change_cart_status(request):
    cart_id = request.GET.get("cart_id")

    cart_obj = Cart.objects.get(pk=cart_id)

    cart_obj.c_is_select = not cart_obj.c_is_select

    cart_obj.save()

    is_all_select = not Cart.objects.filter(c_user=request.user).filter(c_is_select=False).exists()

    data = {
        'status': 200,
        'msg': '修改成功',
        'c_is_select': cart_obj.c_is_select,
        'is_all_select': is_all_select,
        'total_price': get_total_price(),
    }

    return JsonResponse(data=data)


# 购物车减少商品数量
def sub_shopping(request):
    cart_id = request.GET.get("cart_id")

    cart_obj = Cart.objects.get(pk=cart_id)
    data = {
        'status': 200,
        'msg': 'ok',
    }
    obj_num = cart_obj.c_goods_num

    # 如果商品数量大大于1，就减掉，只剩一个了就把这条商品数据删除
    if cart_obj.c_goods_num > 1:
        cart_obj.c_goods_num = cart_obj.c_goods_num - 1
        cart_obj.save()
        data['c_goods_num'] = cart_obj.c_goods_num
    else:
        cart_obj.delete()
        data['c_goods_num'] = 0

    data['total_price'] = get_total_price()

    return JsonResponse(data=data)


# 全选
def all_select(request):
    cart_list = request.GET.get("cart_list")

    cart_list = cart_list.split("#")

    # 先把需要将未选改成选定的card对象拿出来
    carts = Cart.objects.filter(id__in=cart_list)

    for cart_obj in carts:
        cart_obj.c_is_select = not cart_obj.c_is_select
        cart_obj.save()

    data = {
        'status': 200,
        'msg': 'ok',
        'total_price': get_total_price(),
    }

    return JsonResponse(data=data)


# 生成订单
def make_order(request):
    carts = Cart.objects.filter(c_user=request.user).filter(c_is_select=True)
    order = Order()
    order.o_user = request.user
    order.o_price = get_total_price()
    order.save()

    for cart_obj in carts:
        ordergoods = OrderGoods()
        ordergoods.o_order = order
        ordergoods.o_goods_num = cart_obj.c_goods_num
        ordergoods.o_goods = cart_obj.c_goods
        ordergoods.save()
        # 生成订单后把购物车里面的内容删除
        cart_obj.delete()

    data = {
        'status': 200,
        'msg': 'ok',
        'order_id': order.id
    }

    return JsonResponse(data=data)


# 订单详情
def order_detail(request):
    order_id = request.GET.get("orderid")
    order = Order.objects.get(pk=order_id)

    data = {
        'title': '订单详情',
        'order': order,
    }

    return render(request, 'order/order_detail.html', context=data)


# 待付款界面
def order_list_not_pay(request):
    orders = Order.objects.filter(o_user=request.user).filter(o_status=ORDER_STATUS_NOT_PAY)

    data = {
        'title': '订单列表',
        'orders': orders,
    }

    return render(request, 'order/order_list_not_pay.html', context=data)


def payed(request):

    order_id = request.GET.get("order_id")
    order = Order.objects.get(pk=order_id)
    order.o_status = ORDER_STATUS_NOT_SEND
    order.save()
    data = {
        "status":200,
        "msg":"payed success",
    }
    return JsonResponse(data)